<template>
  <div
    ref="rellaxRef"
    class="bo-rellax"
    @mousedown="onMouseDown"
    @wheel="onWheel"
  >
    <div
      ref="wrapRef"
      class="wrap"
    >
      <slot />
    </div>
  </div>
</template>

<script setup>
import { ref, provide, watch, defineEmits, onMounted, nextTick } from '@nuxtjs/composition-api'
import Rellax from 'rellax'

const rellax = ref(null)
const rellaxRef = ref(null)
const wrapRef = ref(null)
const dragging = ref(false)
const positionX = ref(0)
const lastX = ref(0)

const emit = defineEmits(['scroll-change'])

// 鼠标按下
const onMouseDown = (event) => {
  dragging.value = true
  const { clientX } = event
  lastX.value = clientX
}

const setPositionX = (value) => {
  const maxWidth = wrapRef.value.offsetWidth - rellaxRef.value.offsetWidth
  if (value < 0) {
    // 限制最小值
    positionX.value = 0
  } else if (value > maxWidth) {
    // 限制最大值
    positionX.value = maxWidth
  } else {
    positionX.value = value
  }
  rellaxRef.value.scroll(positionX.value, 0)
}

// 鼠标移动
const onMouseMove = (event) => {
  if (dragging.value) {
    const { clientX } = event
    const deltaX = lastX.value - clientX

    const current = deltaX + positionX.value

    setPositionX(current)
    lastX.value = clientX
  }
}

// 鼠标抬起
const onMouseUp = () => {
  console.log('鼠标抬起')
  dragging.value = false
}

const onWheel = (event) => {
  // 阻止事件冒泡
  event.preventDefault()
  console.log('鼠标滚动了')
  const result = event.deltaY > 0 ? positionX.value + 85 : positionX.value - 85
  setPositionX(result)
}

watch(positionX, (newValue, prevValue) => {
  emit('scroll-change', { deltaStatus: newValue > prevValue })
})

provide('positionX', positionX)
provide('rellaxRef', rellaxRef)
provide('wrapRef', wrapRef)

onMounted(() => {
  document.addEventListener('mousemove', onMouseMove)
  document.addEventListener('mouseup', onMouseUp)
  nextTick(() => {
    rellax.value = new Rellax('.rellax-item[data-rellax-item]', {
      horizontal: true,
      vertical: false,
      wrapper: rellaxRef.value
    })
  })
})
</script>

<style>
.bo-rellax {
  width: 980px;
  height: 550px;
  position: relative;
  display: flex;
  user-select: none;
  border: 1px solid salmon;
  overflow-x: scroll;
  overflow-y: hidden;
}

.wrap {
  position: absolute;
  background-color: #f1f3f4;
}

.spacer {
  position: absolute;
  left: 50%;
  top: 0;
  bottom: 0;
  border-left: 1px solid #fa8072;
}
</style>
